package com.example.nettypractice.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;

public class FirstNettyServer {
    private final int port;

    public FirstNettyServer(int port){
        this.port = port;
    }


    public  void start() throws  Exception{

        final FirstNettyServerHandler serverHandler = new FirstNettyServerHandler();

        //NioEventLoopGroup来进行事件的处理，如接受新的连接以及读/写数据
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //ServerBootstrap实例用来引导和绑定服务器
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    //InetSocketAddress来绑定端口，用于监听这个地址的连接请求
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) throws Exception{
                            // 注入对象编码器和解码器
                            channel.pipeline().addLast(new ObjectEncoder());
                            channel.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            channel.pipeline().addLast(serverHandler);

                        }
                    });
            //调用ServerBootstrap.bind()方法来绑定服务器
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}
